package com.opdar.platform.core.convert;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.lang.reflect.Type;

/**
 * Created by shiju on 2017/1/18.
 */
public class DefaultJSONConvert extends JSONConvert {

    @Override
    public Object convert(Object o, Type type) throws Exception {
        if(o != null && o instanceof byte[] && ((byte[]) o).length > 0){
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, true);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
            return objectMapper.readValue((byte[]) o, objectMapper.getTypeFactory().constructType(type));
        }
        return null;
    }

    @Override
    public byte[] serialization(Object o) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
        return objectMapper.writeValueAsBytes(o);
    }
}
